package cn.wp.ewallet.wallet.service.impl;

import cn.wp.common.core.dao.JdbcSupportTemplate;
import cn.wp.common.core.dto.WpResult;
import cn.wp.common.core.model.WpPage;
import cn.wp.common.core.web.WpUserContext;
import cn.wp.ewallet.wallet.dao.UserPublishDao;
import cn.wp.ewallet.wallet.extension.constant.EwalletWalletConstant;
import cn.wp.ewallet.wallet.extension.constant.ExchangeConstant;
import cn.wp.ewallet.wallet.model.dto.WalletShqcAccountInfoDto;
import cn.wp.ewallet.wallet.model.entity.UserOrderDo;
import cn.wp.ewallet.wallet.model.entity.UserPublishDo;
import cn.wp.ewallet.wallet.service.AccountInfoService;
import cn.wp.ewallet.wallet.service.UserPublishService;
import cn.wp.ewallet.wallet.service.WalletInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

import static cn.wp.ewallet.wallet.extension.constant.EwalletWalletConstant.CHECK_AMOUNT_FAILED_CODE;

@Slf4j
@Service
public class UserPublishServiceImpl extends BaseServiceImpl<UserPublishDo> implements UserPublishService {

    public UserPublishServiceImpl(JdbcSupportTemplate jdbcSupportTemplate) {
        super(jdbcSupportTemplate);
    }

    @Autowired
    private WalletInfoService walletInfoService;

    @Autowired
    private UserPublishDao userPublishDao;

    @Autowired
    private AccountInfoService accountInfoService;

    /**
     * 创建发布
     *
     * @param userPublish
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public WpResult pub(UserPublishDo userPublish, String transPwd) {
        userPublish.setUserId(WpUserContext.get().getId());
        // 发布出售
        if (1 == userPublish.getType()) {
            //
            if (Strings.isBlank(transPwd)) {
                return new WpResult().failure(EwalletWalletConstant.CHECK_TRANSPWD_NULL_CODE, "交易密码为空");
            }
            //校验交易密码
            if (!walletInfoService.checkTransPwd(transPwd)) {
                return new WpResult().failure(EwalletWalletConstant.CHECK_TRANSPWD_FAILED_CODE, "交易密码校验失败");
            }
            // 查询可用货币
            WalletShqcAccountInfoDto walletShqcAccountInfo = walletInfoService.getWalletShqcAccountInfo();
            if (walletShqcAccountInfo.getAvailableShqc().compareTo(userPublish.getCount()) < 0) {
                return new WpResult().failure(CHECK_AMOUNT_FAILED_CODE, "账户余额不足");
            } else {
                // 扣除钱包可用 SHQC
                accountInfoService.exchange(walletShqcAccountInfo.getAccountId(), userPublish.getCount().negate());
            }

        }
        userPublish.setUpTime(System.currentTimeMillis());
        userPublish.setStatus(true);
        userPublish.setCounted(BigDecimal.ZERO);
        userPublish.setFrenze(BigDecimal.ZERO);
        this.insert(userPublish);

        return WpResult.suc();
    }

    @Override
    public WpResult depub(String publishId) {
        UserPublishDo publish = select("publish_id = '" + publishId + "'").get(0);
        if (publish.getFrenze().compareTo(BigDecimal.ZERO) == 1) {
            return new WpResult().failure(ExchangeConstant.PUBLISH_FRENZE_CANOT_DOWN_EOR, "有未完成的订单，不能下架");
        }
        // 出售下架
        if (1 == publish.getType()) {
            // 下架完成，退回
            accountInfoService.exchange(accountInfoService.shqcAccountId(publish.getUserId()), publish.getCount().subtract(publish.getCounted()));
        }
        //取消冻结改为已完成
        publish.setStatus(false);
        publish.setDownTime(System.currentTimeMillis() / 1000);
        this.updateByPrimaryKey(publish);
        return new WpResult().success(true);
    }

    /**
     * 发布列表
     *
     * @param type
     * @return
     */
    @Override
    public WpResult pubList(Integer type, String userId, Integer pageNo, Integer pageSize) {
        return WpResult.suc(userPublishDao.pubList(type, userId, pageNo, pageSize));
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void freeze(String id, BigDecimal num) {
        UserPublishDo publish = select("publish_id = '" + id + "'").get(0);
        this.execute(new StringBuilder().append("update user_publish ")
                .append("set frenze = '")
                .append(publish.getFrenze().add(num))
                .append("'")
                .append(" where publish_id = '")
                .append(id).append("'").toString());
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void finish(String id, UserOrderDo order) {
        UserPublishDo publish = select("id = '" + id + "'").get(0);
        //取消冻结改为已完成
        this.execute(new StringBuilder().append("update user_publish ")
                .append("set frenze = '")
                .append(publish.getFrenze().subtract(order.getCount()))
                .append("'")
                .append(",")
                .append("set counted = '")
                .append(publish.getCounted().add(order.getCount()))
                .append("'")
                .append(" where publish_id = '")
                .append(id).append("'").toString());
    }

    @Override
    public void back(String id, BigDecimal num) {
        UserPublishDo publish = select("publish_id = '" + id + "'").get(0);
        this.execute(new StringBuilder().append("update user_publish ")
                .append("set frenze = '")
                .append(publish.getFrenze().subtract(num))
                .append("'")
                .append(" where publish_id = '")
                .append(id).append("'").toString());
    }

    @Override
    public WpResult pubList(Integer type, String userId, WpPage wpPage) {
        return new WpResult().success(userPublishDao.pubList(type, userId, wpPage.getPage(), wpPage.getLimit()));
    }
}
